package br.usp.icmc.lasdpc.gem.ssh;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;


public class SshExample {
	protected static BufferedReader reader = new BufferedReader(
			new InputStreamReader(System.in));

	public static void main(String args[]) {
		SshClient ssh = new SshClient();
		try {
			//System.out.println("Host to connect: ");
			//String hostname = reader.readLine();
			//ssh.connect(hostname);
			//ssh.connect("yellowbird");
			//ssh.connect(hostname, new ConsoleKnownHostsKeyVerification());
			ssh.connect("yellowbird", new IgnoreHostKeyVerification());
			
			PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
			
			//System.out.println("Username: ");
			//String username = reader.readLine();
			//pwd.setUsername(username);
			pwd.setUsername("ljr");
			
			//System.out.println("Password: ");
			//String password = reader.readLine();
			//pwd.setPassword(password);
			pwd.setPassword("s3nhas");
			
			int result = ssh.authenticate(pwd);
			
			if (result == AuthenticationProtocolState.FAILED) {
				System.out.println("The authentication failed");
			} else if (result == AuthenticationProtocolState.PARTIAL) {
				System.out.println("The authentication succeeded but another"
						+ "authentication is required");
			} else if (result == AuthenticationProtocolState.COMPLETE) {
				System.out.println("The authentication is complete");
			} else {
				System.out.println("Unknown authentication result.");
			}
			
			
			SessionChannelClient session = ssh.openSessionChannel();
			session.executeCommand("/bin/sh");
			
			OutputStream out = session.getOutputStream();
			String cmd = "ls\n";
			out.write(cmd.getBytes());
			
			InputStream in = session.getInputStream();
			byte[] buffer = new byte[255];
			int read;
			while ((read = in.read(buffer)) > 0) {
				String out2 = new String(buffer, 0, read);
				System.out.println(out2);
			}
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ssh.disconnect();
		}
	}
}
